import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/chunk_upload.dart';

class UploadTaskItem extends StatelessWidget {
  final UploadTask task;
  final VoidCallback onStart;
  final VoidCallback onPause;
  final VoidCallback onResume;
  final VoidCallback onCancel;
  final VoidCallback onRemove;

  const UploadTaskItem({
    Key? key,
    required this.task,
    required this.onStart,
    required this.onPause,
    required this.onResume,
    required this.onCancel,
    required this.onRemove,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 文件名和类型
            Row(
              children: [
                _buildFileTypeIcon(),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        task.fileName,
                        style: const TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 4),
                      Text(
                        '${task.formattedSize} · ${_getFileType()}',
                        style: TextStyle(color: Colors.grey[600], fontSize: 12),
                      ),
                    ],
                  ),
                ),
                _buildStatusChip(),
              ],
            ),

            const SizedBox(height: 16),

            // 进度条
            LinearProgressIndicator(
              value: task.progress / 100,
              backgroundColor: Colors.grey[200],
              valueColor: AlwaysStoppedAnimation<Color>(_getProgressColor()),
            ),

            const SizedBox(height: 8),

            // 进度信息
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  _getProgressText(),
                  style: TextStyle(color: Colors.grey[600], fontSize: 12),
                ),
                Text(
                  '${task.progress.toStringAsFixed(1)}%',
                  style: TextStyle(color: Colors.grey[600], fontSize: 12),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // 操作按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: _buildActionButtons(),
            ),
          ],
        ),
      ),
    );
  }

  // 构建文件类型图标
  Widget _buildFileTypeIcon() {
    IconData iconData;
    Color iconColor;

    final fileExt = task.fileName.split('.').last.toLowerCase();

    if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].contains(fileExt)) {
      iconData = Icons.image;
      iconColor = Colors.blue;
    } else if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'].contains(fileExt)) {
      iconData = Icons.video_file;
      iconColor = Colors.red;
    } else if (['mp3', 'wav', 'ogg', 'flac', 'aac'].contains(fileExt)) {
      iconData = Icons.audio_file;
      iconColor = Colors.orange;
    } else if (['pdf'].contains(fileExt)) {
      iconData = Icons.picture_as_pdf;
      iconColor = Colors.red;
    } else if (['doc', 'docx'].contains(fileExt)) {
      iconData = Icons.description;
      iconColor = Colors.blue;
    } else if (['xls', 'xlsx'].contains(fileExt)) {
      iconData = Icons.table_chart;
      iconColor = Colors.green;
    } else if (['ppt', 'pptx'].contains(fileExt)) {
      iconData = Icons.slideshow;
      iconColor = Colors.orange;
    } else if (['zip', 'rar', '7z', 'tar', 'gz'].contains(fileExt)) {
      iconData = Icons.folder_zip;
      iconColor = Colors.amber;
    } else {
      iconData = Icons.insert_drive_file;
      iconColor = Colors.grey;
    }

    return Container(
      width: 40,
      height: 40,
      decoration: BoxDecoration(
        color: iconColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Icon(iconData, color: iconColor, size: 24),
    );
  }

  // 构建状态标签
  Widget _buildStatusChip() {
    Color chipColor;
    String statusText = task.statusText;

    switch (task.status) {
      case UploadTaskStatus.pending:
        chipColor = Colors.grey;
        break;
      case UploadTaskStatus.uploading:
        chipColor = Colors.blue;
        break;
      case UploadTaskStatus.paused:
        chipColor = Colors.orange;
        break;
      case UploadTaskStatus.completed:
        chipColor = Colors.green;
        break;
      case UploadTaskStatus.failed:
        chipColor = Colors.red;
        break;
      case UploadTaskStatus.canceled:
        chipColor = Colors.grey;
        break;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: chipColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: chipColor.withOpacity(0.5)),
      ),
      child: Text(statusText, style: TextStyle(color: chipColor, fontSize: 12)),
    );
  }

  // 获取文件类型文本
  String _getFileType() {
    final fileExt = task.fileName.split('.').last.toLowerCase();

    if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].contains(fileExt)) {
      return '图片';
    } else if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'].contains(fileExt)) {
      return '视频';
    } else if (['mp3', 'wav', 'ogg', 'flac', 'aac'].contains(fileExt)) {
      return '音频';
    } else if (['pdf'].contains(fileExt)) {
      return 'PDF文档';
    } else if (['doc', 'docx'].contains(fileExt)) {
      return 'Word文档';
    } else if (['xls', 'xlsx'].contains(fileExt)) {
      return 'Excel表格';
    } else if (['ppt', 'pptx'].contains(fileExt)) {
      return 'PPT演示文稿';
    } else if (['zip', 'rar', '7z', 'tar', 'gz'].contains(fileExt)) {
      return '压缩文件';
    } else {
      return '文件';
    }
  }

  // 获取进度文本
  String _getProgressText() {
    if (task.status == UploadTaskStatus.completed) {
      final dateFormat = DateFormat('yyyy-MM-dd HH:mm');
      return '完成于 ${dateFormat.format(task.completedAt ?? DateTime.now())}';
    } else if (task.status == UploadTaskStatus.failed) {
      return '上传失败: ${task.error ?? "未知错误"}';
    } else if (task.status == UploadTaskStatus.canceled) {
      return '已取消上传';
    } else if (task.type == UploadTaskType.chunk) {
      return '分片上传: ${task.uploadedChunks ?? 0}/${task.totalChunks ?? 0}';
    } else {
      return '普通上传';
    }
  }

  // 获取进度条颜色
  Color _getProgressColor() {
    switch (task.status) {
      case UploadTaskStatus.uploading:
        return Colors.blue;
      case UploadTaskStatus.completed:
        return Colors.green;
      case UploadTaskStatus.failed:
        return Colors.red;
      case UploadTaskStatus.paused:
        return Colors.orange;
      case UploadTaskStatus.canceled:
        return Colors.grey;
      default:
        return Colors.blue;
    }
  }

  // 构建操作按钮
  List<Widget> _buildActionButtons() {
    final buttons = <Widget>[];

    // 根据任务状态显示不同的按钮
    switch (task.status) {
      case UploadTaskStatus.pending:
        buttons.add(
          _buildActionButton(
            icon: Icons.play_arrow,
            tooltip: '开始上传',
            onPressed: onStart,
          ),
        );
        buttons.add(
          _buildActionButton(
            icon: Icons.delete,
            tooltip: '移除任务',
            onPressed: onRemove,
          ),
        );
        break;

      case UploadTaskStatus.uploading:
        buttons.add(
          _buildActionButton(
            icon: Icons.pause,
            tooltip: '暂停上传',
            onPressed: onPause,
          ),
        );
        buttons.add(
          _buildActionButton(
            icon: Icons.cancel,
            tooltip: '取消上传',
            onPressed: onCancel,
          ),
        );
        break;

      case UploadTaskStatus.paused:
        buttons.add(
          _buildActionButton(
            icon: Icons.play_arrow,
            tooltip: '继续上传',
            onPressed: onResume,
          ),
        );
        buttons.add(
          _buildActionButton(
            icon: Icons.cancel,
            tooltip: '取消上传',
            onPressed: onCancel,
          ),
        );
        break;

      case UploadTaskStatus.completed:
        buttons.add(
          _buildActionButton(
            icon: Icons.delete,
            tooltip: '移除任务',
            onPressed: onRemove,
          ),
        );
        break;

      case UploadTaskStatus.failed:
        buttons.add(
          _buildActionButton(
            icon: Icons.refresh,
            tooltip: '重试上传',
            onPressed: onResume,
          ),
        );
        buttons.add(
          _buildActionButton(
            icon: Icons.delete,
            tooltip: '移除任务',
            onPressed: onRemove,
          ),
        );
        break;

      case UploadTaskStatus.canceled:
        buttons.add(
          _buildActionButton(
            icon: Icons.refresh,
            tooltip: '重新上传',
            onPressed: onResume,
          ),
        );
        buttons.add(
          _buildActionButton(
            icon: Icons.delete,
            tooltip: '移除任务',
            onPressed: onRemove,
          ),
        );
        break;
    }

    return buttons;
  }

  // 构建单个操作按钮
  Widget _buildActionButton({
    required IconData icon,
    required String tooltip,
    required VoidCallback onPressed,
  }) {
    return Padding(
      padding: const EdgeInsets.only(left: 8),
      child: IconButton(
        icon: Icon(icon),
        tooltip: tooltip,
        onPressed: onPressed,
        constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
        padding: EdgeInsets.zero,
        iconSize: 20,
      ),
    );
  }
}
